package com.education.springbootdemo.utils;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class MacUtils {

    public static String getMACAddress() {
        // 优先级1：有线接口（排除虚拟接口）
        String mac = findMacAddress(
                Arrays.asList("eth", "en", "本地连接"),  // 有线接口常见名称
                Arrays.asList("vm", "vbox", "virtual", "wsl") // 虚拟接口排除列表
        );

        // 优先级2：无线接口（排除虚拟接口）
        //if (mac == null) {
        if (mac == null) {
            mac = findMacAddress(
                    Arrays.asList("wlan", "wi-fi", "wl"),    // 无线接口常见名称
                    Arrays.asList("vm", "vbox", "virtual", "wsl")
            );
        }

        // 优先级3：虚拟接口
        if (mac == null) {
            mac = findMacAddress(
                    Arrays.asList("vm", "vbox", "virtual", "wsl"), // 虚拟接口标识
                    Collections.emptyList() // 不排除任何接口
            );
        }

        return mac != null ? mac : "未找到有效MAC地址";
    }

    /**
     * 根据接口名称特征查找MAC地址
     * @param includeKeywords 接口名称包含的关键字（OR逻辑）
     * @param excludeKeywords 接口名称排除的关键字（OR逻辑）
     */
    private static String findMacAddress(List<String> includeKeywords, List<String> excludeKeywords) {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();

                // 基础过滤：回环接口、未启用接口、无效MAC
                if (networkInterface.isLoopback() ||
                        !networkInterface.isUp() ||
                        networkInterface.getHardwareAddress() == null) {
                    continue;
                }

                // MAC地址有效性检查
                byte[] macBytes = networkInterface.getHardwareAddress();
                if (macBytes.length != 6) continue;

                // 接口名称处理
                String interfaceName = networkInterface.getName().toLowerCase();

                // 包含关键字检查
                boolean containsInclude = includeKeywords.stream()
                        .anyMatch(keyword -> interfaceName.contains(keyword.toLowerCase()));

                // 排除关键字检查
                boolean containsExclude = excludeKeywords.stream()
                        .anyMatch(keyword -> interfaceName.contains(keyword.toLowerCase()));

                if (containsInclude && !containsExclude) {
                    // 格式转换：字节转十六进制
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < macBytes.length; i++) {
                        sb.append(String.format("%02X%s",
                                macBytes[i] & 0xFF,
                                (i < macBytes.length - 1) ? ":" : "")
                        );
                    }
                    return sb.toString();
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }
}
